62ce971ac68feadf3f3ff0fb6a1a35e280155c35
[lhc/web/wiklou.git] / maintenance / parserTests.inc
1 <?php
2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 # http://www.gnu.org/copyleft/gpl.html
19
20 /**
21 * @todo Make this more independent of the configuration (and if possible the database)
22 * @todo document
23 * @package MediaWiki
24 * @subpackage Maintenance
25 */
26
27 /** */
28 $options = array( 'quick', 'color', 'quiet', 'help' );
29 $optionsWithArgs = array( 'regex' );
30
31 require_once( 'commandLine.inc' );
32 require_once( "$IP/includes/ObjectCache.php" );
33 require_once( "$IP/includes/BagOStuff.php" );
34 require_once( "$IP/languages/LanguageUtf8.php" );
35 require_once( "$IP/includes/Hooks.php" );
36 require_once( "$IP/maintenance/parserTestsParserHook.php" );
37
38 /**
39 * @package MediaWiki
40 * @subpackage Maintenance
41 */
42 class ParserTest {
43 /**
44 * boolean $color whereas output should be colorized
45 * @access private
46 */
47 var $color;
48
49 /**
50 * boolean $lightcolor whereas output should use light colors
51 * @access private
52 */
53 var $lightcolor;
54
55 /**
56 * Sets terminal colorization and diff/quick modes depending on OS and
57 * command-line options (--color and --quick).
58 *
59 * @access public
60 */
61 function ParserTest() {
62 global $options;
63
64 # Only colorize output if stdout is a terminal.
65 $this->lightcolor = false;
66 $this->color = !wfIsWindows() && posix_isatty(1);
67
68 if( isset( $options['color'] ) ) {
69 switch( $options['color'] ) {
70 case 'no':
71 $this->color = false;
72 break;
73 case 'light':
74 $this->lightcolor = true;
75 # Fall through
76 case 'yes':
77 default:
78 $this->color = true;
79 break;
80 }
81 }
82
83 $this->showDiffs = !isset( $options['quick'] );
84
85 $this->quiet = isset( $options['quiet'] );
86
87 if (isset($options['regex'])) {
88 $this->regex = $options['regex'];
89 } else {
90 # Matches anything
91 $this->regex = '';
92 }
93 }
94
95 /**
96 * Remove last character if it is a newline
97 * @access private
98 */
99 function chomp($s) {
100 if (substr($s, -1) === "\n") {
101 return substr($s, 0, -1);
102 }
103 else {
104 return $s;
105 }
106 }
107
108 /**
109 * Run a series of tests listed in the given text file.
110 * Each test consists of a brief description, wikitext input,
111 * and the expected HTML output.
112 *
113 * Prints status updates on stdout and counts up the total
114 * number and percentage of passed tests.
115 *
116 * @param string $filename
117 * @return bool True if passed all tests, false if any tests failed.
118 * @access public
119 */
120 function runTestsFromFile( $filename ) {
121 $infile = fopen( $filename, 'rt' );
122 if( !$infile ) {
123 die( "Couldn't open parserTests.txt\n" );
124 }
125
126 $data = array();
127 $section = null;
128 $success = 0;
129 $total = 0;
130 $n = 0;
131 while( false !== ($line = fgets( $infile ) ) ) {
132 $n++;
133 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
134 $section = strtolower( $matches[1] );
135 if( $section == 'endarticle') {
136 if( !isset( $data['text'] ) ) {
137 die( "'endarticle' without 'text' at line $n\n" );
138 }
139 if( !isset( $data['article'] ) ) {
140 die( "'endarticle' without 'article' at line $n\n" );
141 }
142 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
143 $data = array();
144 $section = null;
145 continue;
146 }
147 if( $section == 'end' ) {
148 if( !isset( $data['test'] ) ) {
149 die( "'end' without 'test' at line $n\n" );
150 }
151 if( !isset( $data['input'] ) ) {
152 die( "'end' without 'input' at line $n\n" );
153 }
154 if( !isset( $data['result'] ) ) {
155 die( "'end' without 'result' at line $n\n" );
156 }
157 if( !isset( $data['options'] ) ) {
158 $data['options'] = '';
159 }
160 else {
161 $data['options'] = $this->chomp( $data['options'] );
162 }
163 if (preg_match('/\\bdisabled\\b/i', $data['options'])
164 || !preg_match("/{$this->regex}/i", $data['test'])) {
165 # disabled test
166 $data = array();
167 $section = null;
168 continue;
169 }
170 if( $this->runTest(
171 $this->chomp( $data['test'] ),
172 $this->chomp( $data['input'] ),
173 $this->chomp( $data['result'] ),
174 $this->chomp( $data['options'] ) ) ) {
175 $success++;
176 }
177 $total++;
178 $data = array();
179 $section = null;
180 continue;
181 }
182 if ( isset ($data[$section] ) ) {
183 die ( "duplicate section '$section' at line $n\n" );
184 }
185 $data[$section] = '';
186 continue;
187 }
188 if( $section ) {
189 $data[$section] .= $line;
190 }
191 }
192 if( $total > 0 ) {
193 $ratio = wfPercent( 100 * $success / $total );
194 print $this->termColor( 1 ) . "\nPassed $success of $total tests ($ratio) ";
195 if( $success == $total ) {
196 print $this->termColor( 32 ) . "PASSED!";
197 } else {
198 print $this->termColor( 31 ) . "FAILED!";
199 }
200 print $this->termReset() . "\n";
201 return ($success == $total);
202 } else {
203 die( "No tests found.\n" );
204 }
205 }
206
207 /**
208 * Run a given wikitext input through a freshly-constructed wiki parser,
209 * and compare the output against the expected results.
210 * Prints status and explanatory messages to stdout.
211 *
212 * @param string $input Wikitext to try rendering
213 * @param string $result Result to output
214 * @return bool
215 */
216 function runTest( $desc, $input, $result, $opts ) {
217 if( !$this->quiet ) {
218 $this->showTesting( $desc );
219 }
220
221 $this->setupGlobals($opts);
222
223 $user =& new User();
224 $options = ParserOptions::newFromUser( $user );
225
226 if (preg_match('/\\bmath\\b/i', $opts)) {
227 # XXX this should probably be done by the ParserOptions
228 require_once('Math.php');
229
230 $options->setUseTex(true);
231 }
232
233 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
234 $titleText = $m[1];
235 }
236 else {
237 $titleText = 'Parser test';
238 }
239
240 $parser =& new Parser();
241 wfRunHooks( 'ParserTestParser', array( &$parser ) );
242 $title =& Title::makeTitle( NS_MAIN, $titleText );
243
244 if (preg_match('/\\bpst\\b/i', $opts)) {
245 $out = $parser->preSaveTransform( $input, $title, $user, $options );
246 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
247 $out = $parser->transformMsg( $input, $options );
248 } else {
249 $output = $parser->parse( $input, $title, $options );
250 $out = $output->getText();
251
252 if (preg_match('/\\bill\\b/i', $opts)) {
253 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
254 } else if (preg_match('/\\bcat\\b/i', $opts)) {
255 $out = $this->tidy ( implode( ' ', $output->getCategoryLinks() ) );
256 }
257
258 $result = $this->tidy($result);
259 }
260
261 $this->teardownGlobals();
262
263 if( $result === $out && $this->wellFormed( $out ) ) {
264 return $this->showSuccess( $desc );
265 } else {
266 return $this->showFailure( $desc, $result, $out );
267 }
268 }
269
270 /**
271 * Set up the global variables for a consistent environment for each test.
272 * Ideally this should replace the global configuration entirely.
273 *
274 * @access private
275 */
276 function setupGlobals($opts = '') {
277 # Save the prefixed / quoted table names for later use when we make the temporaries.
278 $db =& wfGetDB( DB_READ );
279 $this->oldTableNames = array();
280 foreach( $this->listTables() as $table ) {
281 $this->oldTableNames[$table] = $db->tableName( $table );
282 }
283 if( !isset( $this->uploadDir ) ) {
284 $this->uploadDir = $this->setupUploadDir();
285 }
286
287 $settings = array(
288 'wgServer' => 'http://localhost',
289 'wgScript' => '/index.php',
290 'wgScriptPath' => '/',
291 'wgArticlePath' => '/wiki/$1',
292 'wgUploadPath' => 'http://example.com/images',
293 'wgUploadDirectory' => $this->uploadDir,
294 'wgStyleSheetPath' => '/skins',
295 'wgSitename' => 'MediaWiki',
296 'wgLanguageCode' => 'en',
297 'wgContLanguageCode' => 'en',
298 'wgDBprefix' => 'parsertest',
299 'wgDefaultUserOptions' => array(),
300
301 'wgLang' => new LanguageUtf8(),
302 'wgContLang' => new LanguageUtf8(),
303 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
304 'wgMaxTocLevel' => 999,
305 'wgCapitalLinks' => true,
306 'wgDefaultUserOptions' => array(),
307 'wgNoFollowLinks' => true,
308 'wgThumbnailScriptPath' => false,
309 'wgUseTeX' => false,
310 );
311 $this->savedGlobals = array();
312 foreach( $settings as $var => $val ) {
313 $this->savedGlobals[$var] = $GLOBALS[$var];
314 $GLOBALS[$var] = $val;
315 }
316 $GLOBALS['wgLoadBalancer']->loadMasterPos();
317 $GLOBALS['wgMessageCache']->initialise( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
318 $this->setupDatabase();
319
320 global $wgUser;
321 $wgUser = new User();
322 }
323
324 # List of temporary tables to create, without prefix
325 # Some of these probably aren't necessary
326 function listTables() {
327 return array('user', 'page', 'revision', 'text',
328 'pagelinks', 'imagelinks', 'categorylinks', 'templatelinks',
329 'site_stats', 'hitcounter',
330 'ipblocks', 'image', 'oldimage',
331 'recentchanges',
332 'watchlist', 'math', 'searchindex',
333 'interwiki', 'querycache',
334 'objectcache'
335 );
336 }
337
338 /**
339 * Set up a temporary set of wiki tables to work with for the tests.
340 * Currently this will only be done once per run, and any changes to
341 * the db will be visible to later tests in the run.
342 *
343 * @access private
344 */
345 function setupDatabase() {
346 static $setupDB = false;
347 global $wgDBprefix;
348
349 # Make sure we don't mess with the live DB
350 if (!$setupDB && $wgDBprefix === 'parsertest') {
351 # oh teh horror
352 $GLOBALS['wgLoadBalancer'] = LoadBalancer::newFromParams( $GLOBALS['wgDBservers'] );
353 $db =& wfGetDB( DB_MASTER );
354
355 $tables = $this->listTables();
356
357 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
358 # Database that supports CREATE TABLE ... LIKE
359 global $wgDBtype;
360 if( $wgDBtype == 'PostgreSQL' ) {
361 $def = 'INCLUDING DEFAULTS';
362 } else {
363 $def = '';
364 }
365 foreach ($tables as $tbl) {
366 $newTableName = $db->tableName( $tbl );
367 $tableName = $this->oldTableNames[$tbl];
368 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName $def)");
369 }
370 } else {
371 # Hack for MySQL versions < 4.1, which don't support
372 # "CREATE TABLE ... LIKE". Note that
373 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
374 # would not create the indexes we need....
375 foreach ($tables as $tbl) {
376 $res = $db->query("SHOW CREATE TABLE {$this->oldTableNames[$tbl]}");
377 $row = $db->fetchRow($res);
378 $create = $row[1];
379 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
380 . $wgDBprefix . $tbl .'`', $create);
381 if ($create === $create_tmp) {
382 # Couldn't do replacement
383 die("could not create temporary table $tbl");
384 }
385 $db->query($create_tmp);
386 }
387
388 }
389
390 # Hack: insert a few Wikipedia in-project interwiki prefixes,
391 # for testing inter-language links
392 $db->insert( 'interwiki', array(
393 array( 'iw_prefix' => 'Wikipedia',
394 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
395 'iw_local' => 0 ),
396 array( 'iw_prefix' => 'MeatBall',
397 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
398 'iw_local' => 0 ),
399 array( 'iw_prefix' => 'zh',
400 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
401 'iw_local' => 1 ),
402 array( 'iw_prefix' => 'es',
403 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
404 'iw_local' => 1 ),
405 array( 'iw_prefix' => 'fr',
406 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
407 'iw_local' => 1 ),
408 array( 'iw_prefix' => 'ru',
409 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
410 'iw_local' => 1 ),
411 ) );
412
413 # Hack: Insert an image to work with
414 $db->insert( 'image', array(
415 'img_name' => 'Foobar.jpg',
416 'img_size' => 12345,
417 'img_description' => 'Some lame file',
418 'img_user' => 1,
419 'img_user_text' => 'WikiSysop',
420 'img_timestamp' => $db->timestamp( '20010115123500' ),
421 'img_width' => 1941,
422 'img_height' => 220,
423 'img_bits' => 24,
424 'img_media_type' => MEDIATYPE_BITMAP,
425 'img_major_mime' => "image",
426 'img_minor_mime' => "jpeg",
427 ) );
428
429 $setupDB = true;
430 }
431 }
432
433 /**
434 * Create a dummy uploads directory which will contain a couple
435 * of files in order to pass existence tests.
436 * @return string The directory
437 * @access private
438 */
439 function setupUploadDir() {
440 global $IP;
441
442 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
443 mkdir( $dir );
444 mkdir( $dir . '/3' );
445 mkdir( $dir . '/3/3a' );
446
447 $img = "$IP/skins/monobook/headbg.jpg";
448 $h = fopen($img, 'r');
449 $c = fread($h, filesize($img));
450 fclose($h);
451
452 $f = fopen( $dir . '/3/3a/Foobar.jpg', 'wb' );
453 fwrite( $f, $c );
454 fclose( $f );
455 return $dir;
456 }
457
458 /**
459 * Restore default values and perform any necessary clean-up
460 * after each test runs.
461 *
462 * @access private
463 */
464 function teardownGlobals() {
465 foreach( $this->savedGlobals as $var => $val ) {
466 $GLOBALS[$var] = $val;
467 }
468 if( isset( $this->uploadDir ) ) {
469 $this->teardownUploadDir( $this->uploadDir );
470 unset( $this->uploadDir );
471 }
472 }
473
474 /**
475 * Remove the dummy uploads directory
476 * @access private
477 */
478 function teardownUploadDir( $dir ) {
479 unlink( "$dir/3/3a/Foobar.jpg" );
480 rmdir( "$dir/3/3a" );
481 rmdir( "$dir/3" );
482
483 @unlink( "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg" );
484 @rmdir( "$dir/thumb/3/3a/Foobar.jpg" );
485 @rmdir( "$dir/thumb/3/3a" );
486 @rmdir( "$dir/thumb/3/39" ); # wtf?
487 @rmdir( "$dir/thumb/3" );
488 @rmdir( "$dir/thumb" );
489 rmdir( "$dir" );
490 }
491
492 /**
493 * "Running test $desc..."
494 * @access private
495 */
496 function showTesting( $desc ) {
497 print "Running test $desc... ";
498 }
499
500 /**
501 * Print a happy success message.
502 *
503 * @param string $desc The test name
504 * @return bool
505 * @access private
506 */
507 function showSuccess( $desc ) {
508 if( !$this->quiet ) {
509 print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
510 }
511 return true;
512 }
513
514 /**
515 * Print a failure message and provide some explanatory output
516 * about what went wrong if so configured.
517 *
518 * @param string $desc The test name
519 * @param string $result Expected HTML output
520 * @param string $html Actual HTML output
521 * @return bool
522 * @access private
523 */
524 function showFailure( $desc, $result, $html ) {
525 if( $this->quiet ) {
526 # In quiet mode we didn't show the 'Testing' message before the
527 # test, in case it succeeded. Show it now:
528 $this->showTesting( $desc );
529 }
530 print $this->termColor( '1;31' ) . 'FAILED!' . $this->termReset() . "\n";
531 if( $this->showDiffs ) {
532 print $this->quickDiff( $result, $html );
533 }
534 if( !$this->wellFormed( $html ) ) {
535 print "XML error: $this->mXmlError\n";
536 }
537 return false;
538 }
539
540 /**
541 * Run given strings through a diff and return the (colorized) output.
542 * Requires writable /tmp directory and a 'diff' command in the PATH.
543 *
544 * @param string $input
545 * @param string $output
546 * @param string $inFileTail Tailing for the input file name
547 * @param string $outFileTail Tailing for the output file name
548 * @return string
549 * @access private
550 */
551 function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
552 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
553
554 $infile = "$prefix-$inFileTail";
555 $this->dumpToFile( $input, $infile );
556
557 $outfile = "$prefix-$outFileTail";
558 $this->dumpToFile( $output, $outfile );
559
560 $diff = `diff -au $infile $outfile`;
561 unlink( $infile );
562 unlink( $outfile );
563
564 return $this->colorDiff( $diff );
565 }
566
567 /**
568 * Write the given string to a file, adding a final newline.
569 *
570 * @param string $data
571 * @param string $filename
572 * @access private
573 */
574 function dumpToFile( $data, $filename ) {
575 $file = fopen( $filename, "wt" );
576 fwrite( $file, $data . "\n" );
577 fclose( $file );
578 }
579
580 /**
581 * Return ANSI terminal escape code for changing text attribs/color,
582 * or empty string if color output is disabled.
583 *
584 * @param string $color Semicolon-separated list of attribute/color codes
585 * @return string
586 * @access private
587 */
588 function termColor( $color ) {
589 if($this->lightcolor) {
590 return $this->color ? "\x1b[1;{$color}m" : '';
591 } else {
592 return $this->color ? "\x1b[{$color}m" : '';
593 }
594 }
595
596 /**
597 * Return ANSI terminal escape code for restoring default text attributes,
598 * or empty string if color output is disabled.
599 *
600 * @return string
601 * @access private
602 */
603 function termReset() {
604 return $this->color ? "\x1b[0m" : '';
605 }
606
607 /**
608 * Colorize unified diff output if set for ANSI color output.
609 * Subtractions are colored blue, additions red.
610 *
611 * @param string $text
612 * @return string
613 * @access private
614 */
615 function colorDiff( $text ) {
616 return preg_replace(
617 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
618 array( $this->termColor( 34 ) . '$1' . $this->termReset(),
619 $this->termColor( 31 ) . '$1' . $this->termReset() ),
620 $text );
621 }
622
623 /**
624 * Insert a temporary test article
625 * @param string $name the title, including any prefix
626 * @param string $text the article text
627 * @param int $line the input line number, for reporting errors
628 * @static
629 * @access private
630 */
631 function addArticle($name, $text, $line) {
632 $this->setupGlobals();
633 $title = Title::newFromText( $name );
634 if ( is_null($title) ) {
635 die( "invalid title at line $line\n" );
636 }
637
638 $aid = $title->getArticleID( GAID_FOR_UPDATE );
639 if ($aid != 0) {
640 die( "duplicate article at line $line\n" );
641 }
642
643 $art = new Article($title);
644 $art->insertNewArticle($text, '', false, false );
645 $this->teardownGlobals();
646 }
647
648 /*
649 * Run the "tidy" command on text if the $wgUseTidy
650 * global is true
651 *
652 * @param string $text the text to tidy
653 * @return string
654 * @static
655 * @access private
656 */
657 function tidy( $text ) {
658 global $wgUseTidy;
659 if ($wgUseTidy) {
660 $text = Parser::tidy($text);
661 }
662 return $text;
663 }
664
665 /**
666 * Hack up a private DOCTYPE with HTML's standard entity declarations.
667 * PHP 4 seemed to know these if you gave it an HTML doctype, but
668 * PHP 5.1 doesn't.
669 * @return string
670 * @access private
671 */
672 function hackDocType() {
673 global $wgHtmlEntities;
674 $out = "<!DOCTYPE html [\n";
675 foreach( $wgHtmlEntities as $entity => $codepoint ) {
676 $out .= "<!ENTITY $entity \"&#$codepoint;\">";
677 }
678 $out .= "]>\n";
679 return $out;
680 }
681
682 function wellFormed( $text ) {
683 $html =
684 $this->hackDocType() .
685 '<html>' .
686 $text .
687 '</html>';
688
689 $parser = xml_parser_create( "UTF-8" );
690
691 # case folding violates XML standard, turn it off
692 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
693
694 if( !xml_parse( $parser, $html, true ) ) {
695 $err = xml_error_string( xml_get_error_code( $parser ) );
696 $position = xml_get_current_byte_index( $parser );
697 $fragment = $this->extractFragment( $html, $position );
698 $this->mXmlError = "$err at byte $position:\n$fragment";
699 xml_parser_free( $parser );
700 return false;
701 }
702 xml_parser_free( $parser );
703 return true;
704 }
705
706 function extractFragment( $text, $position ) {
707 $start = max( 0, $position - 10 );
708 $before = $position - $start;
709 $fragment = '...' .
710 $this->termColor( 34 ) .
711 substr( $text, $start, $before ) .
712 $this->termColor( 0 ) .
713 $this->termColor( 31 ) .
714 $this->termColor( 1 ) .
715 substr( $text, $position, 1 ) .
716 $this->termColor( 0 ) .
717 $this->termColor( 34 ) .
718 substr( $text, $position + 1, 9 ) .
719 $this->termColor( 0 ) .
720 '...';
721 $display = str_replace( "\n", ' ', $fragment );
722 $caret = ' ' .
723 str_repeat( ' ', $before ) .
724 $this->termColor( 31 ) .
725 '^' .
726 $this->termColor( 0 );
727 return "$display\n$caret";
728 }
729
730 }
731
732 ?>